from pymongo import MongoClient
import datetime
import pandas as pd



# ----------------------
# MongoDB数据加载
# ----------------------
MONGO_URI = "mongodb://172.40.10.141:27017/"
DB_NAME = "innerVehicle"
VEH_COLL = "vehicle_test"
DRV_COLL = "driver_test"
client = MongoClient(MONGO_URI)
db = client[DB_NAME]
db_update = client[DB_NAME]
collection = db_update['driver_test']
vehicle_docs = list(db[VEH_COLL].find({}, {"_id": 0}))
driver_docs = list(db[DRV_COLL].find({}, {"_id": 0}))
vehicle_df = pd.DataFrame(vehicle_docs)
driver_df = pd.DataFrame(driver_docs)

def update_double_zero(collection):
    """更新月双零箔次数 - 只有当所有文值都 >=4 时才减4"""
    try:
        # 首先检查是否所有的 month_double_zero_count 都 >= 4
        count_below_threshold = collection.count_documents(
            {"month_double_zero_count": {"$lt": 4}}
        )
        count_belong_changde = collection.count_documents(
            {"region":"常德"}
        )


        if count_below_threshold > count_belong_changde:
            print(f"存在 {count_below_threshold} 个文档的值小于4，不执行更新操作")
            return

        # 所有文档的值都 >= 4，执行更新操作
        result = collection.update_many(
            {"region":"长沙"},  # 空筛选条件表示匹配所有文档
            {"$inc": {"month_double_zero_count": -4}}  # 使用 $inc 操作符减少4
        )

        print(f"匹配到的文档数: {result.matched_count}")
        print(f"修改的文档数: {result.modified_count}")

        if result.matched_count > 0:
            print("所有文档的月双零箔次数已成功减少4")
        else:
            print("没有找到匹配的文档")

    except Exception as e:
        print(f"更新失败: {e}")

def update_single_top(collection):
    """更新季单顶次数"""
    try:
        result = collection.update_many(
            {},  # 空筛选条件表示匹配所有文档
            {"$set": {"season_single_top_count": 0}}
        )
        print(f"匹配到的文档数: {result.matched_count}")
        print(f"修改的文档数: {result.modified_count}")
        if result.matched_count > 0:
            print("字段更新成功！")
        else:
            print("没有找到匹配的文档")
    except Exception as e:
        print(f"更新失败: {e}")

def update_mongodb(collection):

    today = datetime.date.today()
    today =today+datetime.timedelta(days=1)
    update_double_zero(collection)

    if today.day == 1 and today.month in [1,4,7,10] :
        print('今天将更新季单顶数据')
        update_single_top(collection)


def update_data(result_df, assigned_drivers, assigned_vehicles):

    collection_driver = db_update['driver_test']
    collection_vehicle = db_update['vehicle_test']
    # mongodb数据库更新
    # 未安排人员数据更新
    for data in driver_df[~driver_df['driver_name'].isin(result_df['司机姓名'])]['driver_name']:
        result =collection_driver.update_one(
            {'driver_name': data},
            {
                "$push": {
                    "last_4days_departure_times": {
                        "$each": [None],
                        "$slice": -4  # 只保留最后4个元素
                    }
                },
                '$set': {'end_time': '18:00'}
            }  # 更新操作
        )

    # 未安排车辆数据更新
    for data in vehicle_df[~vehicle_df['plate_number'].isin(result_df['车牌号'])]['plate_number']:
        result =collection_vehicle.update_one(
            {'plate_number': data},
            {
                '$set': {'end_time': '8:00'}
            }  # 更新操作
        )

    for _,data in result_df.iterrows():
        # 更新第一个匹配的文档
        if data['货物类型'] == '双零箔':
            result = collection_driver.update_one(
                {"driver_name": data['司机姓名']},  # 查询条件
                {
                    "$push": {
                        "last_4days_departure_times": {
                            "$each": [data['装货时间']],
                            "$slice": -4  # 只保留最后4个元素
                        }
                    },
                    "$inc": {"month_double_zero_count": 1},
                    '$set': {'end_time': data['收车时间']}
                }  # 更新操作
            )
        elif data['货物类型'] == '单顶':
            result = collection_driver.update_one(
                {"driver_name": data['司机姓名']},  # 查询条件
                {
                    "$push": {
                        "last_4days_departure_times": {
                            "$each": [data['发车时间']],
                            "$slice": -4  # 只保留最后4个元素
                        }
                    },
                    "$inc": {"season_single_top_count": 1},
                    '$set': {'end_time': data['收车时间']}
                }  # 更新操作
            )
        else:
            if collection["driver_name"] == data['司机姓名']:
                print(data)
            result = collection_driver.update_one(
                {"driver_name": data['司机姓名']},
                {
                    "$push": {
                        "last_4days_departure_times": {
                            "$each": [data['发车时间']],
                            "$slice": -4  # 只保留最后4个元素
                        }
                    },
                    '$set': {'end_time': data['收车时间']}
                }
            )
        result1 = collection_vehicle.update_one(
            {"plate_number": data['车牌号']},  # 查询条件
            {
                '$set': {'end_time': data['收车时间']}
            }  # 更新操作
        )
    print(f"匹配了 {result.matched_count} 个文档，修改了 {result.modified_count} 个文档")

    return None